<template>
  <div class="SearchInput">
    <van-cell-group inset>
      <van-field 
        v-model="searchValue" 
        :placeholder="placeholder" 
        :clearable="clearable"
        left-icon="search"
        autocomplete="off"
        @input="handleInput"
        @search="handleSearch"
        @clear="handleClear"
      />
    </van-cell-group>
    <div class="label">搜索</div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, withDefaults } from 'vue';

// 定义接收父组件的参数类型
interface SearchBarProps {
  // v-model绑定的值
  modelValue?: string;
  // 占位文本
  placeholder?: string;
  // 是否显示清除按钮
  clearable?: boolean;
  // 初始值
  defaultValue?: string;
  // 输入防抖时间（毫秒）
  debounceTime?: number;
}

// 使用withDefaults设置默认值（TypeScript方式）
const props = withDefaults(defineProps<SearchBarProps>(), {
  modelValue: '',
  placeholder: '搜索标题、类型、创建人',
  clearable: true,
  defaultValue: '',
  debounceTime: 300
});

// 定义向父组件触发的事件
const emit = defineEmits<{
  (e: 'update:modelValue', value: string): void;
  (e: 'input', value: string): void;
  (e: 'search', value: string): void;
  (e: 'clear'): void;
  (e: 'debouncedInput', value: string): void;
}>();

// 使用modelValue作为内部值，实现v-model双向绑定
const searchValue = ref(props.modelValue || props.defaultValue);

const handleInput = (value: string | Event) => {
  // 处理van-field的input事件，可能传递Event对象或字符串
  const inputValue = typeof value === 'string' ? value : (value.target as HTMLInputElement)?.value || '';
  searchValue.value = inputValue;
  // 更新v-model绑定的值
  emit('update:modelValue', inputValue);
  emit('input', inputValue);
};

const handleSearch = () => {
  emit('search', searchValue.value);
};

const handleClear = () => {
  searchValue.value = '';
  emit('update:modelValue', '');
  emit('clear');
};

// 监听modelValue变化，同步到内部值
watch(
  () => props.modelValue,
  (newValue) => {
    searchValue.value = newValue || '';
  }
);

// 监听内部值变化，触发防抖搜索
let debounceTimer: NodeJS.Timeout;
watch(searchValue, (newValue) => {
  clearTimeout(debounceTimer);
  debounceTimer = setTimeout(() => {
    emit('debouncedInput', newValue);
  }, props.debounceTime);
});

// 监听defaultValue变化（向后兼容）
watch(
  () => props.defaultValue,
  (newValue) => {
    if (!props.modelValue) {
      searchValue.value = newValue || '';
    }
  }
);
</script>

<style scoped>
@import url('./index.scss');
</style>
